package it.intecs.pisa.smarcos.base;


import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
import android.util.AttributeSet;
import android.util.Log;

public class KeyboardsView extends KeyboardView {
	
	private static final String TAG = KeyboardsView.class.getSimpleName();
	
	protected int offset = 0;
	protected int curX,curY;
	protected Context context=null;
	String currChar = "";
	int nClick = 0;
	long clickTime = 0;
	
   public KeyboardsView(Context context, AttributeSet attrs) {
        super(context, attrs);
        
        this.context = context;
   }
   
   public void setOffset(int o){
        offset = o;
    }
   
   
	public boolean handleEvent(int event, float X, float Y) {	   
	   
		Log.d(TAG, "handleEvent");
		
		int i;
		List<Keyboard.Key> keyslist = getKeyboard().getKeys();		
	
		Intent intent = new Intent();
		curX= (int) X;
		curY= (int) (Y - offset - getTop());
		
		switch(event) {

		case GestureEvents.ONSCROLL:

			for (i=0; i < keyslist.size(); i++){

				if ((keyslist.get(i).isInside(curX, curY)) && !(currChar.equals(keyslist.get(i).label))){
					Log.d(TAG, "ONSCROLL " + keyslist.get(i).label + " " + keyslist.get(i).x+ " " + keyslist.get(i).y);
					currChar = (String) keyslist.get(i).label;
					intent.setAction(GestureIntents.INTENT_GESTURE_KEYBOARD_SELECTION);
					break;	
				}
			}
			intent.putExtra(GestureIntents.INTENT_GESTURE_KEYBOARD_CHOICE_VALUE, currChar);
			break;

		case GestureEvents.ONDOUBLETAP:
		case GestureEvents.ONSCROLLUP:
			
			intent.setAction(GestureIntents.INTENT_GESTURE_KEYBOARD_CHOICE);	
			
			if (currChar.equals("")){
				for (i=0; i < keyslist.size(); i++){

					if ((keyslist.get(i).isInside(curX, curY)) && !(currChar.equals(keyslist.get(i).label))){
						Log.d(TAG, "ONDOUBLETAP " + keyslist.get(i).label);
						currChar = (String) keyslist.get(i).label;
						break;	
					}
				}
			}
			
			if (currChar.equals("DEL ALL") && event == GestureEvents.ONSCROLLUP)
				return true;
			
			intent.putExtra(GestureIntents.INTENT_GESTURE_KEYBOARD_CHOICE_VALUE, currChar);
			currChar = "";
			break;
		}
		
	
		intent.addCategory(Intent.CATEGORY_DEFAULT);					
		context.sendBroadcast(intent);
		return true;
   }	
}
